<template>
  <view class="confirm-container"> 
    <!-- 订单商品 -->
    <view class="order-items">
      <view class="card-header">
        <text class="section-title">已选商品</text>
      </view>
      <view class="item-list">
        <view class="item" v-for="(item, index) in cartStore.state.items" :key="index">
          <!-- <view>
            <image :src="item.image" mode="widthFix" class="item-image"></image>
          </view> -->
          <view class="item-left">
            <view class="item-name">{{ item.name }}</view>
            <view class="item-spec" v-if="item.specification">{{ item.specification }}</view>
          </view>
          <view class="item-right">
            <view class="item-quantity">x{{ item.quantity }}</view>
            <view class="item-price">
              <text class="price-symbol">￥</text>
              <text>{{ formatMoney(item.price * item.quantity) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 备注 -->
    <view class="order-remark">
      <view class="card-header">
        <text class="section-title">备注</text>
      </view>
      <view class="remark-input">
        <u-input
          v-model="remark"
          type="textarea"
          placeholder="如有需要，请输入备注信息"
          height="150"
          :border="true"
          :clearable="true"
        ></u-input>
      </view>
    </view>
    
    <!-- 合计 -->
    <view class="order-total">
      <view class="card-header">
        <text class="section-title">金额详情</text>
      </view>
      <view class="total-content">
        <view class="total-row">
          <view class="total-label">商品金额</view>
          <view class="total-value">
            <text class="price-symbol">￥</text>
            <text>{{ formatMoney(cartStore.state.totalPrice) }}</text>
          </view>
        </view>
        <view class="total-row">
          <view class="total-label">配送费</view>
          <view class="total-value">
            <text class="price-symbol">￥</text>
            <text>{{ formatMoney(0) }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-method">
      <view class="card-header">
        <text class="section-title">支付方式</text>
      </view>
      <view class="method-list">
        <view
          class="method-item" 
          @click="selectPaymentMethod('wxpay')"
        >
          <view class="method-icon">
            <u-icon name="weixin-fill" color="#09BB07" size="40"></u-icon>
          </view>
          <view class="method-name">微信支付</view> 
        </view>
      </view>
    </view>
    
    <!-- 提交订单 -->
    <view class="submit-bar">
      <view class="submit-info">
        <view class="submit-total">
          <text>合计：</text>
          <text class="price-symbol">￥</text>
          <text class="price-value">{{ formatMoney(totalAmount) }}</text>
        </view>
      </view>
      <view class="submit-btn">
        <u-button 
          type="primary" 
          size="default" 
          :loading="submitting" 
          @click="submitOrder"
          text="提交订单"
          :customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)'}"
          shape="circle"
        >提交订单</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/common/api/index.js';
import cartStore from '@/common/store/cart.js';
import { formatMoney, showToast, showLoading, hideLoading } from '@/common/utils/util.js';

export default {
  data() {
    return {
      cartStore,
      shopInfo: {},
      tableInfo: {},
      remark: '',
      paymentMethod: 'wxpay', // 默认微信支付
      submitting: false
    };
  },
  
  computed: {
    // 订单总金额
    totalAmount() {
      return cartStore.state.totalPrice;
    }
  },
  
  onLoad() {
    this.initData();
  },
  
  methods: {
    formatMoney,
    
    // 初始化数据
    initData() {
      try {
        // 获取本地存储的餐桌信息
        const tableInfoStr = uni.getStorageSync('tableInfo');
        if (tableInfoStr) {
          const data = JSON.parse(tableInfoStr);
          this.tableInfo = data;
          this.shopInfo = data.shopInfo || {};
        }
        
        // 检查购物车是否为空
        if (cartStore.state.items.length === 0) {
          showToast('购物车为空，请先添加商品');
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (e) {
        console.error('获取餐桌信息失败', e);
      }
    },
    
    // 选择支付方式
    selectPaymentMethod(method) {
      this.paymentMethod = method;
    },
    
    // 提交订单
    async submitOrder() {
      if (cartStore.state.items.length === 0) {
        showToast('购物车为空，请先添加商品');
        return;
      }
      
      this.submitting = true;
      showLoading('提交订单中...');
      
      try {
        // 构建订单数据
        const orderData = {
          tableId: cartStore.state.tableId,
          shopId: cartStore.state.shopId,
          items: cartStore.state.items.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            specification: item.specification
          })),
          totalAmount: this.totalAmount,
          remark: this.remark,
          paymentMethod: this.paymentMethod
        };
        
        // 调用创建订单API
        const res = await api.orderApi.createOrder(orderData);
        
        if (res.code === 0 && res.data) {
          // 创建订单成功
          const orderId = res.data.orderId;
          
          // 清空购物车
          cartStore.clearCart();
          
          // 跳转到支付页面
          this.goToPay(orderId, this.totalAmount);
        } else {
          showToast(res.msg || '创建订单失败');
        }
      } catch (e) {
        console.error('创建订单失败', e);
        showToast('创建订单失败');
      } finally {
        hideLoading();
        this.submitting = false;
      }
    },
    
    // 跳转到支付页面
    goToPay(orderId, totalAmount) {
      // 根据支付方式处理
      if (this.paymentMethod === 'wxpay') {
        this.wxPay(orderId);
      }
    },
    
    // 微信支付
    async wxPay(orderId) {
      showLoading('正在获取支付参数...');
      
      try {
        // 获取微信支付参数
        const res = await api.payApi.getWxPayParams(orderId);
        
        if (res.code === 0 && res.data) {
          const payParams = res.data;
          
          // 调用微信支付
          uni.requestPayment({
            ...payParams,
            success: () => {
              showToast('支付成功', 'success');
              // 跳转到订单详情页
              uni.redirectTo({
                url: `/pages/order/detail?id=${orderId}`
              });
            },
            fail: (err) => {
              console.error('支付失败', err);
              showToast('支付已取消');
              // 跳转到订单列表页
              uni.switchTab({
                url: '/pages/order/list'
              });
            }
          });
        } else {
          showToast(res.msg || '获取支付参数失败');
          // 跳转到订单列表页
          uni.switchTab({
            url: '/pages/order/list'
          });
        }
      } catch (e) {
        console.error('获取支付参数失败', e);
        showToast('获取支付参数失败');
        // 跳转到订单列表页
        uni.switchTab({
          url: '/pages/order/list'
        });
      } finally {
        hideLoading();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.confirm-container {
  min-height: 100vh;
  width: 100%;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.confirm-header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200rpx;
  background: linear-gradient(90deg, #fa436a, #F56C6C);
  border-radius: 0 0 40rpx 40rpx;
  z-index: 0;
}

.shop-info {
  position: relative;
  z-index: 1;
  padding: 30rpx;
}

.shop-info-inner {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.shop-logo {
  margin-right: 20rpx;
}

.shop-info-text {
  flex: 1;
}

.shop-info__name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 6rpx;
}

.shop-info__table {
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.icon-margin {
  margin-right: 6rpx;
}

.order-items, .order-remark, .order-total, .payment-method {
  background-color: #fff;
  margin: 0 30rpx 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.item-list {
  padding: 20rpx 30rpx;
}

.item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.item-left {
  flex: 1;
  overflow: hidden;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 4rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
}

.item-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.item-quantity {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.item-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: baseline;
}

.remark-input {
  padding: 20rpx 30rpx;
}

.total-content {
  padding: 0 30rpx;
}

.total-row {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #333;
  
  &:first-child {
    border-bottom: 1rpx dashed #f5f5f5;
  }
}

.price-symbol {
  font-size: 24rpx;
  color: #fa436a;
}

.method-list {
  padding: 0 30rpx;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5; 
}

.method-icon {
  margin-right: 20rpx;
}

.method-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.method-selected {
  margin-left: 20rpx;
}

.submit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.submit-info {
  flex: 1;
}

.submit-total {
  display: flex;
  align-items: baseline;
  font-size: 28rpx;
  color: #333;
  
  .price-value {
    font-size: 36rpx;
    font-weight: bold;
    color: #fa436a;
  }
}

.submit-btn {
  min-width: 240rpx;
  margin-left: 30rpx;
}
</style> 